﻿using System;
using System.Data;
using System.Net;
using System.Threading;
using System.Windows.Forms;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;

namespace UpFile
{
    public partial class FileManage : Form
    {
        #region 变量
        int userid;
        string username;
        int branchid;
        string NASIP;
        int flag;//判别为图片还是视频文件 0表示图片文件 1表示视频文件
        string uri;
        bool ishead = false;//判别是否是总店在进行下载，删除或者上传操作
        string NASusername = System.Configuration.ConfigurationSettings.AppSettings["LocalUserName"];//NAS用户名
        string NASpassword = System.Configuration.ConfigurationSettings.AppSettings["LocalPassword"];//NAS密码
        string firstURL = System.Configuration.ConfigurationSettings.AppSettings["URL"];
        string ImageURL = System.Configuration.ConfigurationSettings.AppSettings["ImageURL"];//图片存储二级地址
        string VideoURL = System.Configuration.ConfigurationSettings.AppSettings["VideoURL"];//视频存储二级地址
        string HeadNASIP = System.Configuration.ConfigurationSettings.AppSettings["HeadNASIP"];//总店NAS_IP
        string HeadNasUsername = System.Configuration.ConfigurationSettings.AppSettings["HeadUserName"];//总店NAS用户名
        string HeadNasPassword = System.Configuration.ConfigurationSettings.AppSettings["HeadPassword"];//总店NAS密码
        static DataTable filelist;
        #endregion

        #region 构造函数
        public FileManage()
        {
            InitializeComponent();
            userid = 0;
            username = "";
            branchid = 0;
            NASIP = "";
        }
        //重载
        public FileManage(int user_id, string user_name, int branch_id, string NAS_IP)
        {
            try
            {
                userid = user_id;
                username = user_name;
                branchid = branch_id;
                NASIP = NAS_IP;
                InitializeComponent();
                if (HeadNASIP == NASIP)
                {
                    ishead = true;
                }
                this.dti_startTimeFrom.Value = DateTime.Now.AddMonths(-1);
                this.dti_startTimeTo.Value = DateTime.Now;
                UpImage.UpFileSoapClient server = new UpImage.UpFileSoapClient();
                filelist = server.GetfileList(true, branchid).Tables[0];
                UserPageToolBind(filelist);
                DataBind(filelist);
                string[] arrTitle = new string[filelist.Rows.Count];
                string[] arrUser = new string[filelist.Rows.Count];
                string[] arrBranch = new string[filelist.Rows.Count];
                for (int i = 0; i < arrTitle.Length; i++)
                {
                    arrTitle[i] = filelist.Rows[i][3].ToString();
                    arrUser[i] = filelist.Rows[i][5].ToString();
                    arrBranch[i] = filelist.Rows[i][7].ToString();
                }
                this.txt_branch.AutoCompleteCustomSource.AddRange(arrBranch);
                this.txt_title.AutoCompleteCustomSource.AddRange(arrTitle);
                this.txb_user.AutoCompleteCustomSource.AddRange(arrUser);
            }
            catch (Exception)
            {
                this.Close();
            }
        }
        #endregion

        #region 数据绑定
        public void DataBind(DataTable table)
        {
            this.dgrfile.Columns.Clear();
            this.dgrfile.DataSource = table;
            this.dgrfile.Columns[1].HeaderCell.Value = "文件类型";
            int count = table.Rows.Count;
            for (int i = 0; i < count; i++)
            {
                if (table.Rows[i][1].ToString() == "1" || table.Rows[i][1].ToString() == "视频")
                {
                    this.dgrfile.Rows[i].Cells[1].Value = "视频";
                }
                if (table.Rows[i][1].ToString() == "0" || table.Rows[i][1].ToString() == "图片")
                {
                    this.dgrfile.Rows[i].Cells[1].Value = "图片";
                }
            }
            this.dgrfile.Columns[0].Visible = false;
            this.dgrfile.Columns[2].Visible = false;
            this.dgrfile.Columns[3].HeaderCell.Value = "文件主题";
            this.dgrfile.Columns[4].HeaderCell.Value = "上传时间";
            this.dgrfile.Columns[5].HeaderCell.Value = "上传人";
            this.dgrfile.Columns[6].HeaderCell.Value = "是否设置";
            this.dgrfile.Columns[6].ReadOnly = true;
            this.dgrfile.Columns[7].HeaderCell.Value = "上传分店";
            this.dgrfile.Columns[8].HeaderCell.Value = "文件项目备注";
            this.dgrfile.Columns[9].Visible = false;
            this.dgrfile.Columns[10].Visible = false;
            this.dgrfile.Columns[11].Visible = false;
        }
        #endregion

        #region 格式绑定
        public void FormBing()
        {

            this.dgrfile.ColumnHeadersDefaultCellStyle.Font = new Font("宋体", 10, FontStyle.Bold, GraphicsUnit.Point);
            this.dgrfile.ColumnHeadersDefaultCellStyle.BackColor = SystemColors.GradientInactiveCaption;
            this.dgrfile.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dgrfile.DefaultCellStyle.Font = new Font("宋体", 9, FontStyle.Regular, GraphicsUnit.Point);
            this.dgrfile.DefaultCellStyle.BackColor = Color.Empty;

        }

        #endregion

        #region 绑定UserPageTool控件
        public void UserPageToolBind(DataTable table)
        {
            this.userPageTool1.Dgv = this.dgrfile;
            this.userPageTool1.Dt = table;
            this.userPageTool1.InitDataSet(8);
            if (table.Rows.Count > 0)
            {
                this.dgrfile.CurrentCell = this.dgrfile.Rows[0].Cells[1];
            }
            FormBing();
        }
        #endregion

        #region 文件删除
        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult result = MessageBox.Show("确定要删除该项吗？", "信息提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                if (result == DialogResult.OK)
                {
                    if (this.dgrfile.SelectedRows.Count > 0)
                    {

                        string cellvalue = dgrfile.CurrentRow.Cells[0].Value.ToString();
                        string branchStrID = branchid.ToString();
                        int cellindex = dgrfile.SelectedCells[0].RowIndex;
                        UpImage.UpFileSoapClient server = new UpImage.UpFileSoapClient();
                        DataSet fileinfo = server.GetfileInfo(cellvalue);
                        //数据库表删除操作
                        server.Delete(cellvalue);
                        server.DeleteFile(cellvalue, branchStrID, ishead);
                        this.dgrfile.Rows.RemoveAt(cellindex);
                        //NAS文件删除操作
                        try
                        {
                            string name = fileinfo.Tables[0].Rows[0]["URLOriginal"].ToString();
                            flag = Convert.ToInt32(fileinfo.Tables[0].Rows[0]["TYPE"].ToString());
                            string itemsToDelete = name.Substring(name.LastIndexOf(@"/") + 1);
                            if (flag == 1)
                            {
                                uri = "ftp://" + NASIP + "/" + firstURL + VideoURL + itemsToDelete;
                            }
                            if (flag == 0)
                            {
                                uri = "ftp://" + NASIP + "/" + firstURL + ImageURL + itemsToDelete;
                            }
                            Thread DeleteThread = new Thread(DeleteFile);
                            DeleteThread.Start();
                        }
                        catch (Exception)
                        {
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show("请在FTP文件浏览器中选择条目！");
                        return;
                    }
                }
            }
            catch
            {
                MessageBox.Show("文件删除失败！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }
        #endregion

        #region 文件删除方法
        public void DeleteFile()
        {
            try
            {
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                reqFTP.UseBinary = true;
                if (ishead)
                {
                    reqFTP.Credentials = new NetworkCredential(HeadNasUsername, HeadNasPassword);
                }
                else
                {
                    reqFTP.Credentials = new NetworkCredential(NASusername, NASpassword);
                }
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                WebResponse response = reqFTP.GetResponse();
                response.Close();
                MessageBox.Show("文件删除成功！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception)
            {
                MessageBox.Show("FTP删除文件失败！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }
        #endregion

        /// <summary>
        /// 文件上传按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnupLoad_Click(object sender, EventArgs e)
        {
            UploadFile form = new UploadFile(userid, username, branchid, NASIP, ishead);//通过调用文件上传构造函数传值(用户信息)
            form.Show();
            this.Hide();
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            Download form = new Download(userid, username, branchid, NASIP, ishead);//通过调用文件下载构造函数传值(用户信息)
            form.Show();
            this.Hide();
        }
        /// <summary>
        /// 窗口关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FileManage_FormClosed(object sender, FormClosedEventArgs e)
        {
            System.Environment.Exit(0);
        }

        /// <summary>
        /// 编号效果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgrfile_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            try
            {
                for (int i = 0; i < dgrfile.Rows.Count; i++)
                {
                    int j = i + 1;
                    dgrfile.Rows[i].HeaderCell.Value = j.ToString();
                }
            }
            catch (Exception)
            {
                return;
            }

        }
        /// <summary>
        /// 根据条件进行查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_search_Click(object sender, EventArgs e)
        {
            string TimeFrom;
            string TimeTo;
            string FileTitle;
            string FileUserName;
            string FileBranchName;
            if (dti_startTimeFrom.Value.ToString() == "")
            {
                this.dti_startTimeFrom.Value = DateTime.Now.AddMonths(-1);
            }
            if (dti_startTimeTo.Value.ToString() == "")
            {
                this.dti_startTimeTo.Value = DateTime.Now;
            }
            TimeFrom = dti_startTimeFrom.Text + " " + "00:00:00 ";
            TimeTo = dti_startTimeTo.Text + " " + "23:59:59 ";
            if (txt_title.Text.ToString() != null)
            {
                FileTitle = txt_title.Text.ToString();
            }
            else
            {
                FileTitle = "";
            }
            if (txb_user.Text.ToString() != null)
            {
                FileUserName = txb_user.Text.ToString();
            }
            else
            {
                FileUserName = "";
            }
            if (txt_branch.Text.ToString() != null)
            {
                FileBranchName = txt_branch.Text.ToString();
            }
            else
            {
                FileBranchName = "";
            }
            string strWhere = "1>0";
            if (FileTitle != "")
            {
                strWhere += string.Format(" and FILE_TITEL like '%{0}%'", FileTitle);
            }
            if (FileUserName != "")
            {
                strWhere += string.Format(" and USERNAME like '%{0}%'", FileUserName);
            }
            if (FileBranchName != "")
            {
                strWhere += string.Format(" and BRANCH_NAME like '%{0}%'", FileBranchName);
            }
            DataTable newdt = new DataTable();
            newdt = filelist.Clone(); // 克隆dt 的结构，包括所有 dt 架构和约束,并无数据；
            strWhere += string.Format(" and UPTIME>'{0}' and UPTIME<'{1}'", TimeFrom, TimeTo);
            strWhere += string.Format(" and ISFLAG='{0}'", checkState.Checked);
            DataRow[] rows = filelist.Select(strWhere); // 从dt 中查询符合条件的记录；
            foreach (DataRow row in rows)  // 将查询的结果添加到dt中；
            {
                newdt.Rows.Add(row.ItemArray);
            }
            UserPageToolBind(newdt);
            DataBind(newdt);
        }


        /// <summary>
        ///DataGridview控件项双击查看预览事件 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgrfile_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int index = e.RowIndex;
            string strUrl = this.dgrfile.CurrentRow.Cells[10].Value.ToString();
            string strName = this.dgrfile.CurrentRow.Cells[2].Value.ToString();
            string strType = this.dgrfile.CurrentRow.Cells[1].Value.ToString();
            if (ishead)
            {
                strUrl = "ftp://" + HeadNASIP + "/" + strUrl;
            }
            else
            {
                strUrl = "ftp://" + NASIP + "/" + strUrl;
            }
            if (strType == "0" || strType == "图片")
            {
                ShowPhoto form = new ShowPhoto(strUrl, strName);//通过调用文件下载构造函数传值(用户信息)
                form.Show();
            }
            if (strType == "1" || strType == "视频")
            {
                PlayVdio form = new PlayVdio(strUrl, strName);//通过调用文件下载构造函数传值(用户信息)
                form.Show();
            }
        }

        private void btn_exit_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }

    }
}
